package com.zhongshengnetwork.rightbe.Adv.activity;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.MyUriUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.activity.WhiteBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.gsonmodel.AdvModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LifeResultModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.my.activity.SettingsActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import pl.droidsonroids.gif.GifImageView;

public class SplashActivity extends Activity {

    private RelativeLayout advertView;
    private Button delayTimeBtn;
    private GifImageView advertImg;
    private ImageView launchimg;

    private boolean isHasAdv = false;
    private int delayTime = 3;//5 广告6秒倒计时
    private boolean isGoToMain; //用于手动点击跳过 后线程中的跳转取消

    private int taskCount = 0;

    private LifeResultModel lifeResultModel = null;

    private String langid = null;

    private boolean isFirstLoad = false;


    private void showTip(){//提示语修改：在你未阅读并勾选同意《用户协议》和《隐私政策》之前，仅能进行部分内容浏览，你可以选择继续浏览或者退出。

        final CustomDialog.Builder builder = new CustomDialog.Builder(SplashActivity.this);
        builder.setTitle("用户协议和隐私政策");
        builder.setMessage("微句（以下简称 \"我们\"）深知个人信息对您的重要性，并会尽全力保护您的个人信息安全可靠。我们致力于维护您对我们的信任，恪守以下原则：权责一致原则、目的明确原则、选择同意原则、最少够用原则、确保安全原则、主体参与原则、公开透明原则等。同时，我们承诺，我们将按业界成熟的安全标准，采取相应的安全保护措施来保护您的个人信息。请在使用我们的产品或服务前，仔细阅读并了解《用户协议》和《隐私政策》。如您同意，请点击同意开始接受我们的服务。");
        builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.FirstViewLoadFlag, false);
                CustomApplication.customApplication.initSDK();//初始化SDK
                taskCount = 3;
                startMain();
            }
        });
        builder.setNegativeButton("不同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                killAppProcess();
                //finish();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.msgTextView.setText("微句（以下简称 \"我们\"）深知个人信息对您的重要性，并会尽全力保护您的个人信息安全可靠。我们致力于维护您对我们的信任，恪守以下原则：权责一致原则、目的明确原则、选择同意原则、最少够用原则、确保安全原则、主体参与原则、公开透明原则等。同时，我们承诺，我们将按业界成熟的安全标准，采取相应的安全保护措施来保护您的个人信息。请在使用我们的产品或服务前，仔细阅读并了解");
        SpannableString clickString = new SpannableString("《用户协议》");
        clickString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent webIntent = new Intent(SplashActivity.this, MyWebActivity.class);
                webIntent.putExtra("FirstFlag", true);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
                startActivity(webIntent);//用户协议
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#87cefa"));//设置颜色
            }
        }, 0, clickString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialog.msgTextView.append(clickString);
        dialog.msgTextView.append("和");
        SpannableString clickString2 = new SpannableString("《隐私政策》");
        clickString2.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent webIntent = new Intent(SplashActivity.this, MyWebActivity.class);
                webIntent.putExtra("FirstFlag", true);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuprivacy.do");
                startActivity(webIntent);//隐私政策
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#87cefa")); //设置颜色
            }
        }, 0, clickString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialog.msgTextView.append(clickString2);
        dialog.msgTextView.append(new SpannableString("。如您同意，请点击同意开始接受我们的服务。"));
        dialog.msgTextView.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
        dialog.show();
    }

    public void killAppProcess()
    {
        //注意：不能先杀掉主进程，否则逻辑代码无法继续执行，需先杀掉相关进程最后杀掉主进程
        ActivityManager mActivityManager = (ActivityManager)SplashActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> mList = mActivityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : mList)
        {
            if (runningAppProcessInfo.pid != android.os.Process.myPid())
            {
                android.os.Process.killProcess(runningAppProcessInfo.pid);
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        langid = getIntent().getStringExtra("langid");
        //Log.e("TAG","1启动获取唯一langid="+langid);
        lifeResultModel =  (LifeResultModel) getIntent().getSerializableExtra("push");

        /*
        // 所有子类都将继承这些相同的属性,请在设置界面之后设置
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)  //使用该属性必须指定状态栏的颜色，不然状态栏透明，很难看
                .init();
        */
        setContentView(R.layout.activity_result_activity);
        //这里设置为app正常态
        AppUtils.getInstance().setAppStatus(AppUtils.STATUS_NORMAL);

        initAdvert();
        initData();
        initListener();
        getHomeData();
        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (flag == true && CommonUtils.isLogin() == false ){
            AppUtils.getInstance().setUserAgreeStatus(false);
        }else {
            //初始化用户同意状态
            AppUtils.getInstance().setUserAgreeStatus(true);
            //初始化高德地图
            CustomApplication.customApplication.initLocation();
            //初始化极光统计
            //JAnalyticsInterface.setDebugMode(false);
            //JAnalyticsInterface.init(CustomApplication.mContext);
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /*
        // 如果你的app可以横竖屏切换，并且适配4.4或者emui3手机请务必在onConfigurationChanged方法里添加这句话
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)  //使用该属性必须指定状态栏的颜色，不然状态栏透明，很难看
                .init();
        */
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        //ImmersionBar.with(this).destroy();
    }

    private void initAdvert() {
        advertImg = (GifImageView) findViewById(R.id.advert_img);
        advertView = (RelativeLayout) findViewById(R.id.advert_view);
        delayTimeBtn = (Button) findViewById(R.id.delay_time_btn);
        launchimg = (ImageView) findViewById(R.id.launchimg);

        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (flag == false || CommonUtils.isLogin() == true ){
            String filePath = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.AdvImgPath,"");
            if (!CommonUtils.isEmpty(filePath)){
                //Log.e("TAG","广告图片路径是："+filePath+"\n");
                boolean status = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.AdvStatus,false);
                if (AdvertUtils.fileIsExists(filePath) && status == true){
                    isHasAdv = true;
                    advertImg.setImageURI(MyUriUtils.getUri(CustomApplication.mContext,filePath));
                }
            }
        }
        advertImg.setVisibility(View.INVISIBLE);
        delayTimeBtn.setVisibility(View.INVISIBLE);

    }
    private void initData() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                advertView.setVisibility(View.VISIBLE);
                delayTimeBtn.post(new Runnable() {
                    @Override
                    public void run() {
                        if (delayTime > 0) {
                            if (delayTime == 3){
                                if (isHasAdv == true){
                                    launchimg.setVisibility(View.INVISIBLE);
                                    advertImg.setVisibility(View.VISIBLE);
                                    delayTimeBtn.setVisibility(View.VISIBLE);
                                }else {
                                    taskCount+=1;
                                    if (!isGoToMain){
                                        startMain();
                                    }
                                    return;
                                }
                            }
                            delayTimeBtn.setText(delayTime + "  跳过");
                            delayTime--;
                            delayTimeBtn.postDelayed(this,1000);
                        }else {
                            taskCount += 1;
                            if (!isGoToMain){
                                startMain();
                            }

                        }
                    }
                });
            }
        }, 1000);

    }
    @Override
    protected void onResume() {
        super.onResume();

        if (isFirstLoad == false){
            isFirstLoad = true;
            boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
            if (CommonUtils.isLogin() == false && flag == true){
                showTip();
            }
        }

        //此处的loadUrl 可以是动态获取的 图片格式可以是png jpg gif ,都可以 ，保存的格式会根据下载链接的后缀进行命名
        //String loadUrl = "http://static.jiazhuang.com/Public/images/start.gif";
        //String loadUrl = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.AdvBgUrl,"");
        //loadAdvertImg(loadUrl,AdvertUtils.AdvImgPath);
    }
    private void loadAdvertImg(final String advertUrl, final String key) {
        if (!TextUtils.isEmpty(advertUrl)) {
            final String[] split = advertUrl.split("/");
            File advert = CustomApplication.mContext.getExternalFilesDir("advert");
            //final File file = new File(advert, System.currentTimeMillis() + split[split.length - 1]);
            final File file = new File(advert,  split[split.length - 1]);
            if (AdvertUtils.fileIsExists(file.toString())){
                //Log.e("file", "文件存在了："+file.toString());
            }else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Log.e("file", "保存路径："+file.toString());
                        try {
                            AdvertUtils.onSaveBitmap(advertUrl, file.toString(),CustomApplication.mContext,key);
                            removeFootList(file.toString(),key);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }

        } else {
            // 获取服务器路径为空时，保存空本地路径，则不显示广告图
            removeFootList("",AdvertUtils.AdvImgPath);
        }

    }


    private void removeFootList(String filePath, String key) {
        String oldFilePath = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(key,"");
        if (!CommonUtils.isEmpty(oldFilePath) && !oldFilePath.equals(filePath)){
            if (AdvertUtils.fileIsExists(oldFilePath)) {
                File f = new File(oldFilePath);
                f.delete();
            }
        }
    }

    private void initListener() {
        delayTimeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                taskCount = 3;
                isGoToMain = true;
                startMain();
            }
        });
    }
    void startMain() {
        if (SplashActivity.this == null){
            return;
        }
        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (CommonUtils.isLogin() == false && flag == true){//未同意隐私协议
            return;
        }
        if (taskCount >= 2){
            //taskCount = 0;
            if(isMainThread() == true){
                Intent intent = new Intent();
                intent.setClass(SplashActivity.this, MainActivity.class);
                //這裡設置flag還是比較 重要的
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                if (lifeResultModel != null){
                    Bundle b=new Bundle();
                    b.putSerializable("push", lifeResultModel);//序列化
                    intent.putExtras(b);//发送数据
                }else {
                    if (!CommonUtils.isEmpty(langid)){
                        intent.putExtra("langid", langid);
                    }
                }
                startActivity(intent);
                finish();
            }else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setClass(SplashActivity.this, MainActivity.class);
                        //這裡設置flag還是比較 重要的
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        if (lifeResultModel != null){
                            Bundle b=new Bundle();
                            b.putSerializable("push", lifeResultModel);//序列化
                            intent.putExtras(b);//发送数据
                        }else {
                            if (!CommonUtils.isEmpty(langid)){
                                intent.putExtra("langid", langid);
                            }
                        }
                        startActivity(intent);
                        finish();
                    }
                });
            }
        }
    }

    public boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    public void onClickBg(View view){

        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (CommonUtils.isLogin() == false && flag == true){//未同意隐私协议
            return;
        }

        boolean status = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.AdvStatus,false);
        if (status == true){
            String url = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.AdvContentUrl,"");
            if (!CommonUtils.isEmpty(url)){
                isGoToMain = true;
                Intent intent = new Intent();
                intent.setClass(SplashActivity.this, MainActivity.class);
                //這裡設置flag還是比較 重要的
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra(APIKey.urlKey,url);
                if (lifeResultModel != null){
                    Bundle b=new Bundle();
                    b.putSerializable("push", lifeResultModel);//序列化
                    intent.putExtras(b);//发送数据
                }else {
                    if (!CommonUtils.isEmpty(langid)){
                        intent.putExtra("langid", langid);
                    }
                }
                startActivity(intent);
                finish();
            }

        }

    }


    private void getHomeData(){
        /*
        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        }else {
            map.put(APIKey.tokenKey, "1");
        }
        String url = "miniapp/appid/getsubjectname.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {// usersign
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","数据："+data+"\n");
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    SPManageUtils.getInstance(mContext).putSPString(AdvertUtils.HomeData,data);
                    taskCount += 1;
                    startMain();
                }
            }
            @Override
            public void onError(String msg) {
                taskCount += 1;
                startMain();
            }
        });
        */
        taskCount += 1;
        startMain();
    }


}